﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using TSSTaskBasicClass;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using TSSControlLibrary;
using TaskSchedulingSystemForm.TaskMonitor;
using TaskSchedulingSystemForm.Model;
using TaskSchedulingSystemForm.Common;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace TaskSchedulingSystemForm
{

    public partial class MainForm : Form
    {
        //反序列化任务信息配置文件
        public static TaskConfig config;
        //维护一个正在执行的任务的线程id池 用来控制是否显示当前执行任务的信息输出
        public static Dictionary<int, bool> CarryNowTaskIdPool;
        //维护一个正在执行的任务池
        public static List<TaskModel> taskCarryNowLst = new List<TaskModel>();
        //维护一个正在执行的任务的任务工作类实例池
        public static Dictionary<int, ABasicTaskWork> taskWorkObjectPool = new Dictionary<int, ABasicTaskWork>();
        //声明一个自定义控件 用来展示某一任务的消息输出
        DisPlayIOInfoUserControl user = new DisPlayIOInfoUserControl();
        
        /// <summary>
        /// 主界面构造函数
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            config = LocalCacheFactory.FromFile<TaskConfig>("TaskConfig.xml");
           // LoadConfigurationResources();
            CarryNowTaskIdPool = new Dictionary<int, bool>();
        }
       /// <summary>
       /// 主页面加载
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                //显示程序的版本号
                this.Text = string.Format("天相数据抓取任务调度系统({0})",Application.ProductVersion);

                TSSLog.WrriteXTLog("应用程序启动，正在初始化数据......");
                CreateTree();
                this.panel_right.Controls.Add(user);
                user.TabIndex = 0;
                user.TabStop = true;
                Console.SetIn(new UserControlReader(user));
                //初始化自定义的输入输出
                DIYConsole.InitializeConsole(taskCarryNowLst,WriteMsgToControl);
                TSSLog.WrriteXTLog("数据初始化完成，开始监视任务调度......");

                //启动任务执行触发器
                TaskTrigger TTrigger = new TaskTrigger(config);
                TTrigger.FreshenMainForm = FreshenMainForm;
                TTrigger.Start();
               
            }
            catch(Exception ex)
            {
                TSSLog.WrriteXTLog(TSSOP.TSSError.ToString()+":系统异常！");
            }
        }
        /// <summary>
        /// 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string s = Console.ReadLine();
         }     
        /// <summary>
        /// 菜单树点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_click(object sender, EventArgs e)
        {
            //暂无需求不实现
        }
        /// <summary>
        /// 创建任务总览树表
        /// </summary>
        private void CreateTree()
        {
            treeView_TaskTotal.Nodes.Clear();
            foreach (var taskType in config.allTaskType)
            {
                TreeNode taskTypeTreeNode = new TreeNode();
                taskTypeTreeNode.Text = taskType.TypeName;
                treeView_TaskTotal.Nodes.Add(taskTypeTreeNode);
                foreach (var task in taskType.taskLst)
                {
                    TreeNode taskTreeNode = new TreeNode();
                    taskTreeNode.Text = task.taskName + "(未运行)";
                    taskTypeTreeNode.Nodes.Add(taskTreeNode);
                    taskTreeNode.ContextMenuStrip = this.contextMenuStrip_tree;
                }
            }
        }
        /// <summary>
        /// 加载应用程序配置资源
        /// </summary>
        private void LoadConfigurationResources()
        {
            foreach (var type in config.allTaskType)
            {
                foreach (var task in type.taskLst)
                {
                    task.ass = Assembly.LoadFrom(task.taskDllPath);
                }
            }
        }
        /// <summary>
        /// 检查任务执行状态
        /// </summary>
        private void CheckTaskCarryStatus()
        {          
            foreach (var taskType in config.allTaskType)
            {
                foreach (var task in taskType.taskLst)
                {
                    if (task.isRunTask)
                    {                 
                        for (int i = 0; i < this.treeView_TaskTotal.Nodes.Count;i++ )
                        {
                            var nodeType = this.treeView_TaskTotal.Nodes[i];
                            for (int j = 0; j < nodeType.Nodes.Count; j++)
                            {
                                var nodeTask = nodeType.Nodes[j];
                                if (nodeTask.Text.ToString() == task.taskName + "(未运行)")
                                {
                                    //nodeTask.Text  = task.taskName + "(正在执行)";
                                    Action action = delegate
                                    {
                                        nodeTask.Text = task.taskName + "(正在执行)";
                                    };
                                    treeView_TaskTotal.Invoke(action);
                                    Action action2 = delegate
                                    {
                                        this.listBox_CarryNow.Items.Add(task.taskName + "(正在执行)");
                                    };
                                    listBox_CarryNow.Invoke(action2);
                                }
                            }
                        }
                    }
                    else
                    {
                         for (int i = 0; i < this.treeView_TaskTotal.Nodes.Count;i++ )
                        {
                            var nodeType = this.treeView_TaskTotal.Nodes[i];
                            for (int j = 0; j < nodeType.Nodes.Count; j++)
                            {
                                var nodeTask = nodeType.Nodes[j];
                                if (nodeTask.Text.ToString() == task.taskName + "(正在执行)")
                                {
                                    Action action = delegate
                                    {
                                        nodeTask.Text = task.taskName + "(未运行)";
                                    };
                                    treeView_TaskTotal.Invoke(action);
                                    //切换任务或者任务结束后  进度条清零
                                    Action actionUpdateProgressBar1 = delegate
                                    {
                                        this.progressBar1.Value = 0;
                                    };
                                    progressBar1.Invoke(actionUpdateProgressBar1);
                                                  
                                    if (listBox_CarryNow.Items.Count > 1)
                                    {
                                        Action action5 = delegate
                                        {
                                            listBox_CarryNow.SelectedIndex = 0;
                                        };
                                        listBox_CarryNow.Invoke(action5);
                                        Action action6 = delegate
                                        {
                                            label_name.Text = "当前显示任务:" + listBox_CarryNow.SelectedItem.ToString().Replace("(正在执行)", "");
                                        };
                                        user.Invoke(action6);
                                    }
                                    else
                                    {
                                        Action action4 = delegate
                                        {
                                            user.richTextBox1.Text = "";
                                            label_name.Text = "当前显示任务:";
                                        };
                                        user.Invoke(action4);
                                        
                                    }
                                    if (listBox_CarryNow.Items.Count >= 1)
                                    {
                                        Action action3 = delegate
                                        {
                                            listBox_CarryNow.Items.Remove(task.taskName + "(正在执行)");
                                        };
                                        listBox_CarryNow.Invoke(action3);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 正在执行任务鼠标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_CarryNow_MouseDown(object sender, MouseEventArgs e)
        {     
            if (e.Button == MouseButtons.Left)
            {
                if (this.listBox_CarryNow.Items.Count == 0)
                {
                    return;
                }
                string taskName = this.listBox_CarryNow.SelectedItem.ToString().Replace("(正在执行)", "");
                label_name.Text = "当前显示任务:" + taskName;
                if (taskName != null)
                {
                    foreach(var taskType in config.allTaskType)
                    {
                        foreach (var task in taskType.taskLst)
                        {
                            if (task.taskName == taskName)
                            {
                                List<int> lstkey = new List<int>();
                                lstkey.AddRange(CarryNowTaskIdPool.Keys);
                                foreach (var key in lstkey)
                                {
                                    CarryNowTaskIdPool[key] = false;
                                }
                                CarryNowTaskIdPool[task.taskThreadId] = true;
                                user.richTextBox1.Clear();
                                user.richTextBox1.Text = task.taskContext;
                                user.ResetoldLenth(task.taskContext.Length);
                            }
                        }
                    }
                }
            }        
        }
     /// <summary>
     /// 处理任务传回的输出请求
     /// </summary>
     /// <param name="msg"></param>
     /// <param name="requestTaskId"></param>
        private void WriteMsgToControl(string msg, int requestTaskId)
        {
            try
            {         
                //处理调度系统的输出请求
                bool is_WriteToControl = CarryNowTaskIdPool[Convert.ToInt32(requestTaskId)];
                foreach (var ta in taskCarryNowLst)
                {
                    if (ta.taskThreadId == requestTaskId)
                    {
                        ta.taskContext += msg + "\r\n";
                        if (is_WriteToControl)
                        {
                            user.WriteOneLine(msg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TSSLog.WrriteXTLog("消息输出时出错 Error:" + ex.StackTrace.ToString() + ex.Message);
                this.progressBar1.Value = 0;
                Mail.SendMail(TSSOP.TSSError, ex.Message + ex.StackTrace);
            }           
        }
        /// <summary>
        /// 单击启动任务项时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_start_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个树节点！", "错误操作提示信息！");
            }
            else if (node.Text.ToString().Contains("正在执行"))
            {
                MessageBox.Show("任务已经在执行，不需要在启动。","错误操作提示信息！");
            }
            else
            {
                //执行手动调度
                foreach(var type in config.allTaskType)
                {
                    foreach(var task in type.taskLst)
                    {
                        if (task.taskName == node.Text.Replace("(未运行)", ""))
                        {
                            TaskTrigger t = new TaskTrigger(config);
                            t.FreshenMainForm = FreshenMainForm;
                            t.DoTaskSchelingMethodByhand(task);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 单击停止任务时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_stop_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个树节点！","错误操作提示信息！");
            }
            else if (node.Text.ToString().Contains("未运行"))
            {
                MessageBox.Show("任务未在执行状态，不需要在停止。","错误操作提示信息！");
            }
            else
            {
                foreach (var type in config.allTaskType)
                {
                    foreach (var task in type.taskLst)
                    {
                        if (task.taskName == node.Text.Replace("(正在执行)", ""))
                        {
                            if (!taskWorkObjectPool[task.taskThreadId].KillTheTaskTherad())
                            {
                                MessageBox.Show("终止任务失败！", "操作提示信息");
                                TSSLog.WrriteXTLog(task, TSSOP.StopTaskFaild);
                            }
                            else
                            {
                                TSSLog.WrriteXTLog(task, TSSOP.StopTask);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 新建任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateNewTask cnt = new CreateNewTask(config);
            cnt.StartPosition = FormStartPosition.CenterParent;
            cnt.FreshenTree = FreshenMainForm;
            cnt.ShowDialog();
           
        }
        /// <summary>
        /// 刷新主界面
        /// </summary>
        /// <param name="opCommand">刷新操作类型</param>
        private void FreshenMainForm(int opCommand)
        {
            switch (opCommand)
            {
                case 1: CreateTree(); break;
                case 2: CheckTaskCarryStatus(); break;
                case 3: UpdateProgressBar(); break;
            }
        }
        /// <summary>
        /// 正在执行任务列表索引值改变触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_CarryNow_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox_CarryNow.Items.Count == 0)
            {
                return;
            }
            string taskName = this.listBox_CarryNow.SelectedItem.ToString().Replace("(正在执行)", "");
            label_name.Text = "当前显示任务:" + taskName;
            if (taskName != null)
            {
                foreach (var taskType in config.allTaskType)
                {
                    foreach (var task in taskType.taskLst)
                    {
                        if (task.taskName == taskName)
                        {
                            List<int> lstkey = new List<int>();
                            lstkey.AddRange(CarryNowTaskIdPool.Keys);
                            foreach (var key in lstkey)
                            {
                                CarryNowTaskIdPool[key] = false;
                            }
                            CarryNowTaskIdPool[task.taskThreadId] = true;                       
                            user.richTextBox1.Clear();
                            user.richTextBox1.Text = task.taskContext;
                            user.ResetoldLenth(task.taskContext.Length);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 在正在执行任务中终止任务时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 终止任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object  item = listBox_CarryNow.SelectedItem;
            if (item == null)
            {
                MessageBox.Show("请选中一个树节点！", "错误操作提示信息！");
            }
            else
            {
                foreach (var type in config.allTaskType)
                {
                    foreach (var task in type.taskLst)
                    {
                        if (task.taskName == item.ToString().Replace("(正在执行)", ""))
                        {
                            if (!taskWorkObjectPool[task.taskThreadId].KillTheTaskTherad())
                            {
                                MessageBox.Show("终止任务失败！", "操作提示信息");
                                TSSLog.WrriteXTLog(task, TSSOP.StopTaskFaild);
                            }
                            else
                            {
                                TSSLog.WrriteXTLog(task, TSSOP.StopTask);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 修改任务的执行时间规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改任务配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个树节点！", "错误操作提示信息！");
            }
            else if (node.Text.ToString().Contains("正在执行"))
            {
                MessageBox.Show("任务正在执行无法修改器配置信息。", "错误操作提示信息！");
            }
            else
            {
                foreach (var type in config.allTaskType)
                {
                    foreach (var task in type.taskLst)
                    {
                        if (task.taskName == node.Text.Replace("(未运行)", ""))
                        {
                            AlterTaskCronRole al = new AlterTaskCronRole(task,config);
                            al.StartPosition = FormStartPosition.CenterParent;
                            al.ShowDialog();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 查看任务上一次执行日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 查看最近一次日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个任务！", "错误操作提示信息！");
            }
            else if (node.Text.ToString().Contains("正在执行"))
            {
                MessageBox.Show("任务正在执行,日志信息可在右侧切换查看。", "提示信息！");
            }
            else
            {
                foreach (var type in config.allTaskType)
                {
                    foreach (var task in type.taskLst)
                    {
                        if (task.taskName == node.Text.Replace("(未运行)", ""))
                        {
                            //调用文本编辑器打开
                            string logPath = @"D:\tuhc\TSStaskLog\lookTaskLastLog.txt";
                            TSSLog.WriteTaskLastLog(logPath, task.taskContext);
                            System.Diagnostics.Process.Start(logPath);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 查看任务的历史日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 查看历史日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个任务！", "错误操作提示信息！");
            }         
            else
            {
                foreach (var type in config.allTaskType)
                {
                    foreach (var task in type.taskLst)
                    {
                        if (task.taskName == node.Text.Replace("(未运行)", "").Replace("(正在执行)", ""))
                        {
                            //调用文本编辑器打开任务的历史日志文件
                            string txtPath = string.Format(@"D:\tuhc\TSStaskLog\{0}.txt",task.taskName);
                            if (txtPath == "")
                            {
                                MessageBox.Show("没有已经选择的txt文件");
                                return;
                            }
                            if (!string.IsNullOrEmpty(txtPath))
                            {
                                try
                                {
                                    System.Diagnostics.Process.Start(txtPath);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(this, ex.Message);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView_TaskTotal.SelectedNode as TreeNode;
            if (node == null)
            {
                MessageBox.Show("请选中一个任务！", "错误操作提示信息！");
            }
            else if (node.Text.ToString().Contains("正在执行"))
            {
                MessageBox.Show("任务正在执行,无法删除任务信息请先结束任务执行！", "错误操作提示信息！");
            }
            else
            {
                for (int i=0; i < config.allTaskType.Count;i++ )
                {
                    for (int j = 0; j < config.allTaskType[i].taskLst.Count;j++)
                    {
                        TaskModel task = config.allTaskType[i].taskLst[j];
                        if (task.taskName == node.Text.Replace("(未运行)", ""))
                       {                           
                            config.allTaskType[i].taskLst.Remove(task);
                            LocalCacheFactory.ToFile<TaskConfig>("TaskConfig.xml", config);
                            FreshenMainForm(1);
                        }
                    }
                }
            }
        }   
        /// <summary>
        /// 查看系统日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 查看系统日志ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            TSSLog.lookTSSLog();
        }
        /// <summary>
        /// 更新进度条
        /// </summary>
        /// <param name="t"></param>
        private void UpdateProgressBar()
        {
            foreach (var v in CarryNowTaskIdPool)
            {
                if (v.Value)
                {
                    foreach (var taskType in config.allTaskType)
                    {
                        foreach (var task in taskType.taskLst)
                        {
                            if (v.Key == task.taskThreadId)
                            {
                                Action action = delegate
                                {
                                    this.progressBar1.Value = task.taskProcess;
                                };
                                progressBar1.Invoke(action);
                            }
                        }
                    }
                }
            }          
        }
    }
}
